import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message,
} from 'antd'

import { useEffect, useState, useRef } from 'react'
import { Link, useHistory, useParams } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { reqPublishUpload, getArticleById } from '@/store/actions'

import { Channels } from '@/components/Channels'
import ReactQuill from 'react-quill'
import { PlusOutlined } from '@ant-design/icons'

import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'

export const Publish = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const { id } = useParams()
  const isEdit = id !== undefined
  const [form] = Form.useForm()
  // 用来表示已经上传的文件列表[图片列表数据]
  // 图像文件是一个对象有很多属性（url）
  // [{url:''}{url:''}]
  const [fileList, setFileList] = useState([])

  // 控制上传数量
  const [count, setCount] = useState(1)
  const fileListRef = useRef([])
  // 一进来就判断是否为编辑模式
  useEffect(() => {
    const loadData = async () => {
      if (!isEdit) return
      const {
        title,
        channel_id,
        content,
        cover: { type, images },
      } = await dispatch(getArticleById(id))
      // 运用表单实例进行回显
      form.setFieldsValue({
        title,
        channel_id,
        content,
        type,
      })

      const newList = images.map((item) => ({ url: item }))

      setFileList(newList)

      // 限制最大上传数量
      setCount(type)

      //将图片存到ref中
      fileListRef.current = newList
    }
    loadData()
  }, [dispatch, id, isEdit, form])

  // 控制上传
  const changeCount = (e) => {
    setCount(e.target.value)
  }
  // 图片发生上传改变
  const onUploadChange = (val) => {
    console.log('图片', val)
    const newFileList = val.fileList.map((file) => {
      // 有响应数据的时候
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      }
      // 不然，返回源文件继续执行
      return file
    })
    // console.log(newFileList)
    setFileList(newFileList)
  }

  // 文件发布提交
  const onFinish = async (val) => {
    // 发布
    saveArticle(val, '发布文章成功')
  }

  // 封装发布或是草稿
  const saveArticle = async (values, msg, isDraft) => {

    // 上传数量验证
    if (values.type !== fileList.length) {
      return message.warning('与要求上传的数量不一致')
    }
    const { type, ...res } = values
    const data = {
      ...res,
      cover: {
        type,
        images: fileList.map((item) => item.url),
      },
    }

    if (isEdit) {
      // 添加id属性
      data.id = isEdit
      msg = '编辑文章成功'
      dispatch(reqPublishUpload(data,isDraft,isEdit))
    }

    await dispatch(reqPublishUpload(data, isDraft))
    message.success(msg, 1, () => {
      history.push('/home/article')
    })
  }

  // 草稿发布提交
  const onSaveDraft = async () => {
    // 触发表单检验斌返回值
    const values = await form.validateFields()
    try {
      saveArticle(values, '存入草稿成功', true)
    } catch {}
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {isEdit ? '编辑文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: '' }}
          onFinish={onFinish}
          // 将创建好的Form 设置为 Form 组件的 Form属性
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 300 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Channels width={300}></Channels>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item
              name="type"
              rules={[{ required: true, message: '请上传图片' }]}
            >
              <Radio.Group onChange={changeCount}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
                {/* <Radio value={-1}>自动</Radio> */}
              </Radio.Group>
            </Form.Item>

            {count !== 0 ? (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                multiple={count === 3}
                action="http://geek.itheima.net/v1_0/upload"
                maxCount={count}
                fileList={fileList}
                onChange={onUploadChange}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            ) : (
              ''
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {isEdit ? '编辑文章' : '发布文章'}
              </Button>
              <Button size="large" onClick={onSaveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
